from tools.models import Photo
from tools.lib.serializer import PhotoSerializer
from datetime import datetime
import random
from django.conf import settings
from crypto.lib.verification import libhash

class UploadPhoto:
    @staticmethod
    def save_photo(img):
        ext = img.name.split('.')[-1]
        if ext not in settings.ALLOWED_IMG_TYPE:
            return Util.say_no({"text":"非法格式"})
        result = {}
        time_rand = datetime.now().strftime('%Y%m%d%H%M%S') + str(random.randint(10000,99999))
        fname = libhash.sha256(time_rand)[:32]+'.'+ext
        path = settings.UPLOAD_ADDRESS + fname
        with open(path,'wb') as f:  
            for i in img.chunks():
                f.write(i)
        result['title'] = fname
        result['location'] = path
        serializer = PhotoSerializer(data=result) 
        if serializer.is_valid(): 
            serializer.save() 
            return (True,path)
        return (False,serializer.errors)
